from urllib import request

import requests
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync


import json
kefulist= []
userkefulist = {}
class ChatConsumer(WebsocketConsumer):  # 继承WebsocketConsumer
   room_name = 'chat_all_data'
   def websocket_connect(self, message):
        print("有人进行连接了。。。。")
        #判断是客服还是用户
        self.group_name = self.scope['url_route']['kwargs']['group']
        async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
        # # kefu = self.group_name.find('kefu')
        # kefustr =  self.group_name.split('kefu')
        # roomstr =  self.group_name.split('room')
        # #是客服
        # if len(kefustr)>1:
        #     #找到了将客服id加入客服列表中
        #     kefulist.append(str(kefustr[1]))
        #     #给前端发送用户列表
        #     async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
        # elif len(roomstr)>1:
        #     async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
        # else:
        #     #把用户id加入到组中
        #     async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
        #     #如果是用户分配客服 获取客服列表 this.chatname+"room"+this.kefuid
        #     userid = self.group_name
        #     key = hash(userid)%len(kefulist)
        #     kefuid = str(kefulist[key])

        #     # roomname = self.group_name+"room"+kefuid
        #     # async_to_sync(self.channel_layer.group_add)(roomname, self.channel_name)
        #     #userkefulist = {"1":[{“id”:1,'name':'zs'}},2,4],'2':[10,12,14]}
        #     #给用户分配客服，存入字典中，key客服id  value分配用户的列表
        #     if  kefuid  in  userkefulist:
        #         userkefulist[kefuid].append(userid)
        #     else:
        #         userkefulist[kefuid] = [userid]
        #     #发送用户列表
        #     channel_layer = get_channel_layer()
        #     #获取此客服对应的用户列表
        #     send_data = userkefulist[kefuid]
           
        #     async_to_sync(channel_layer.group_send)(
        #         'kefu'+str(kefuid),#房间组名
        #         {
        #             'type':'send_to_chrome', #消费者中处理的函数
        #             'data':send_data
        #         }
        #     )
            
        #如果客服以客服id为组加入组，把客服id加入列表【1，2，4】
        
        
        # # self.channel_layer.group_add(self.group_name,self.channel_name)
        
        
       
      
       # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
        self.accept()
       

   def websocket_receive(self, message):
       # 浏览器基于 WebSocket 向后端发送数据，自动触发接收消息
       
        data = json.loads(message['text'])
        channel_layer = get_channel_layer()
        
        if data['from'].find('user') == -1:
            #根据用户查询医生
            async_to_sync(channel_layer.group_send)(
                'user1',#房间组名
                {
                    'type':'send_to_chrome', #消费者中处理的函数
                    'data':data['message']
                }
            )
        else:
            res = requests.post('fastapi',data={"message":data['message']})
            print("####")
            async_to_sync(channel_layer.group_send)(
                'doctor1',#房间组名
                {
                    'type':'send_to_chrome', #消费者中处理的函数
                    'data':data['message']
                }
            )
              
        
        #1客服发给用户
    #    {'type':1,'from':this.chatname,'to':this.kefuid,'message':this.sendms}
        # if 'type' in data:
        #     if int(data['type']) == 1:
        #         print("***发送给用户")
        #         #发给用户
        #         userid = data['from']
        #         channel_layer = get_channel_layer()
                
        #         async_to_sync(channel_layer.group_send)(
        #             userid,#房间组名
        #             {
        #                 'type':'send_to_chrome', #消费者中处理的函数
        #                 'data':data['message']
        #             }
        #         )
        #     else:
        #         #发给客服
        #         channel_layer = get_channel_layer()
        #         #查找客服id
        #         kefuid = 0
        #         for k,v in userkefulist.items():
        #             if data['from'] in v:
        #                 kefuid=k
                        
        #         room = data['from']+"room"+kefuid
        #         async_to_sync(channel_layer.group_send)(
        #             room,#房间组名
        #             {
        #                 'type':'send_to_chrome', #消费者中处理的函数
        #                 'data':data['message']
        #             }
        #         )
            
        

       
    

   def websocket_disconnect(self, message):
       # 客户端向服务端断开连接时，自动触发
        print("连接断开！！")
        self.group_name = self.scope['url_route']['kwargs']['group']
        
        
        async_to_sync(self.channel_layer.group_discard)(
            self.group_name,
            self.channel_name
        )
        raise StopConsumer()
    #自定义的处理房间组内的数据
   def send_to_chrome(self, event):
        try:
            data = event.get('data')
            #接收房间组广播数据，将数据发送给websocket
            self.send(json.dumps(data,ensure_ascii=False))
        except Exception as e:
            pass


